import React, {Component} from 'react';
import {Alert, AsyncStorage, Image, StyleSheet, Text, TouchableOpacity, View} from 'react-native';
import SwipeCards from 'react-native-swipe-cards';
import Toast from '@remobile/react-native-toast';
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';

export default class New extends Component {

    static navigationOptions = ({navigation, screenProps}) => ({
        tabBarLabel: '发现',
        tabBarIcon: ({tintColor, focused}) => (
            focused ?
                <Image style={{
                    height: utils.autoWidth(23),
                    width: utils.autoWidth(27)
                }} resizeMode='contain' source={require('./../../../img/new_select3x.png')}/>
                :
                <Image style={{
                    height: utils.autoWidth(23),
                    width: utils.autoWidth(27)
                }} resizeMode='contain' source={require('./../../../img/new_no3x.png')}/>
        ),
        title: "发现",
        headerStyle: {
            backgroundColor: '#F6F6F6',
            borderBottomWidth: utils.autoWidth(0.5),
            borderColor: '#B2B2B2',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerLeft: null,

    });

    constructor(props) {
        super(props);
        this.cardIndex = 0;
        this.state = {
            size: 50,
            page: 0,
            role: null,
            cards: [],
            cardsDataStatus: true,
            swiperShow: false,
            outOfCards: false,
            butStatus: false,
        }
    }

    componentDidMount() {
        let param = {size: this.state.size, page: this.state.page,};
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/user/styleUser', xToken, param, (res) => {
                if (res.code == 200) {
                    this.setState({
                        cards: res.apiData.content,
                        outOfCards: res.apiData.last,
                        page: res.apiData.number,
                    });
                }
            });
        });

        setTimeout(() => {
            this.setState({
                swiperShow: true
            });
        }, 15);

        console.log(this.state.cards);
        console.log(this.state.cards.length)

    }

    render() {
        let swipeCardsView = <SwipeCards
            ref={'swiper'}
            cards={this.state.cards}
            containerStyle={styles.containerStyle}
            yupStyle={styles.yupStyle}
            yupTextStyle={styles.yupTextStyle}
            nopeStyle={styles.nopeStyle}
            nopeTextStyle={styles.nopeTextStyle}
            loop={false}
            renderCard={(cardData) =>
                <View style={styles.card}>
                    <TouchableOpacity onPress={this.toProfileView.bind(this)}>
                        <Image style={styles.thumbnail}
                               source={{uri: utils.qiniuUrl + cardData.headerImg + utils.qiniu500Url}}/>
                        <View style={styles.profileView}>
                            <View style={styles.profileUpView}>
                                <Text style={[styles.nickNameText]} >{cardData.username}</Text>
                                <Text style={styles.incomeText}>{cardData.priceValue}</Text>
                            </View>
                            <View style={styles.profileBottomView}>
                                <Text style={[styles.markText, {fontStyle:"italic"}]} numberOfLines={1}>{cardData.mark}</Text>
                            </View>
                        </View>
                    </TouchableOpacity>
                </View>
            }
            renderNoMoreCards={this.noMore.bind(this)}
            handleYup={this.handleYup.bind(this)}
            handleNope={this.handleNope.bind(this)}
            cardRemoved={this.cardRemoved.bind(this)}
        />;

        return (
            <View style={styles.pageView}>
                {swipeCardsView}
                {this.state.cards.length - this.cardIndex + 1 !== 0 && this.state.cards.length !== 0?
                    <View style={styles.buttonView}>
                        <TouchableOpacity onPress={() => this.nopeOrYup(0)}>
                            <Image style={styles.imgButton} source={require('./../../../img/nope3x.png')}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.nopeOrYup(1)}>
                            <Image style={styles.imgButton} source={require('./../../../img/rlike3x.png')}/>
                        </TouchableOpacity>
                        <TouchableOpacity onPress={() => this.toChatPage()}>
                            <Image style={styles.imgButton} source={require('./../../../img/like3x.png')}/>
                        </TouchableOpacity>
                    </View>
                    :
                    null}
            </View>
        );
    }

    handleYup() {
        let swiperCards = this.refs['swiper'];
        this.likeOrNo(1, swiperCards.getCurrentCard().id);

        if (this.state.cards.length - this.cardIndex + 1 < 25 && !this.state.outOfCards) {
            this.addCards()
        }
    }

    handleNope() {
        let swiperCards = this.refs['swiper'];
        this.likeOrNo(0, swiperCards.getCurrentCard().id);

        console.log(this.state.cards);

        if (this.state.cards.length - this.cardIndex + 1 < 25 && !this.state.outOfCards) {
            this.addCards()
        }

    }

    noMore() {
        return (
            <View style={styles.noMoreCard}>
                <Text>无数据！</Text>
            </View>
        )
    }

    /*底部的两种按钮*/
    async nopeOrYup(type) {
        let swiperCards = this.refs['swiper'];
        if (!this.state.butStatus) {
            await this.setState({butStatus: true,});
            setTimeout(async () => {
                await this.setState({butStatus: false})
            }, 800);
            Toast.hide();
            if (swiperCards.props.cards.length > 0) {
                let oldCard = swiperCards.props.cards[this.cardIndex];
                console.log(swiperCards.props.cards);
                this.cardIndex = this.cardIndex + 1;
                swiperCards.setState({
                    card: swiperCards.props.cards[this.cardIndex],
                });
                swiperCards._goToNextCard();
                this.likeOrNo(type, oldCard.id);
            }
        } else {
            Toast.hide();
            Toast.showShortBottom("老铁点太快啦~");
        }

        if (this.state.cards.length - this.cardIndex + 1 < 25 && !this.state.outOfCards) {
            this.addCards()
        }
    }

    /*重写的删除卡片事件*/
    async cardRemoved(index) {
        console.log(index)
    }

    /*补充cards*/
    addCards = () => {
        let param = {size: this.state.size, page: this.state.page + 1,};
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/user/styleUser', xToken, param, (res) => {
                this.setState({
                    cards: this.state.cards.concat(res.apiData.content),
                    outOfCards: res.apiData.last,
                    page: res.apiData.number,
                });
            });
        });
    };
    /*接口请求喜欢或者不喜欢*/
    likeOrNo = (type, cardId) => {
        /*0:不喜欢，1:收藏*/
        if (type === 0 || type === 1) {
            let param = {
                userId: cardId,
                type: type
            };
            AsyncStorage.getItem("XToken").then((xToken) => {
                FetchUtils.postWithParamHeader(utils.apiUrl + '/user/likeOrNo', param, xToken, (res) => {
                    if (res.code !== 200) {
                        Toast.showShortBottom(res.msg + " : " + res.apiData);
                    }
                });
            });
        }
    };

    /*前往详情页*/
    toProfileView = () => {
        let swiperCards = this.refs['swiper'];
        let {navigate} = this.props.navigation;
        navigate('StyleManProfileNav', {userId: swiperCards.state.card.id, role: swiperCards.state.card.role})
    };

    /*聊天窗口*/
    toChatPage = () => {
        let swiperCards = this.refs['swiper'];
        let param = {
            userId: swiperCards.state.card.id,
        };
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/user/singerUserInfo', xToken, param, (res) => {
                console.log(res);
                if (res.code === 200) {
                    let {navigate} = this.props.navigation;
                    navigate('ChatPageNav', {toUser: res.apiData});
                } else {
                    Alert.alert("警告", res.apiData);
                }
            })
        });
    };
};
const styles = StyleSheet.create({
    pageView: {
        flex: 1,
        flexDirection: 'column',
        backgroundColor: '#F6F6F6',
    },
    buttonView: {
        flexDirection: 'row',
        justifyContent: 'space-around',
        marginLeft: utils.autoWidth(80),
        marginRight: utils.autoWidth(80),
    },
    imgButton: {
        width: utils.autoWidth(54),
        height: utils.autoWidth(54),
    },
    containerStyle: {
        paddingTop: utils.autoheight(15),
        paddingBottom: utils.autoheight(8, 5),
        width: utils.screenWidth,
        alignItems: 'center',
    },
    yupStyle: {
        paddingTop: utils.autoheight(5),
        borderColor: 'red',
        borderWidth: utils.autoWidth(2),
        position: 'absolute',
        bottom: utils.autoWidth(50),
        right: utils.autoWidth(50),
        width: utils.autoWidth(50),
        height: utils.autoWidth(50),
        borderRadius: utils.autoWidth(25),
    },
    yupTextStyle: {
        alignSelf: 'center',
        fontSize: utils.setSpText(16),
        color: 'red',
    },
    nopeStyle: {
        paddingTop: utils.autoheight(5),
        borderColor: 'black',
        borderWidth: utils.autoWidth(2),
        position: 'absolute',
        bottom: utils.autoWidth(50),
        left: utils.autoWidth(50),
        width: utils.autoWidth(50),
        height: utils.autoWidth(50),
        borderRadius: utils.autoWidth(25),
    },
    nopeTextStyle: {
        alignSelf: 'center',
        fontSize: utils.setSpText(16),
        color: 'black',
    },
    noMoreCard: {
        alignItems: 'center',
    },
    card: {
        flexDirection: 'column',
        alignItems: 'center',
        alignSelf: 'center',
        borderRadius: 7,
        overflow: 'hidden',
        backgroundColor: '#fff',
        elevation: 1,//底部导航栏阴影
        shadowColor: '#000000',
        shadowOffset: {h: 2, w: 2},
        shadowRadius: 7,
        shadowOpacity: 0.05,
        width: utils.autoWidth(300),
        height: utils.autoheight(433),
    },
    thumbnail: {
        marginTop: utils.autoheight(14),
        width: utils.autoWidth(277),
        height: utils.autoheight(343),
        alignSelf: 'center',
    },
    profileView: {
        width: utils.autoWidth(300),
    },
    profileUpView: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        marginLeft: utils.autoWidth(12),
        marginRight: utils.autoWidth(16),
        marginTop: utils.autoheight(15),
    },
    nickNameText: {
        fontSize: utils.setSpText(20),
        color: '#010101',
    },
    incomeText: {
        fontSize: utils.setSpText(15),
        color: '#010101',
    },
    markText: {
        fontSize: utils.setSpText(15),
        color: '#ABABAB',
    },
    profileBottomView: {
        marginLeft: utils.autoWidth(12),

    },
})